package com.hunantv.mglive.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * @author liujianjiu
 *
 * 正方形ImageView ，高度适应宽度
 */
public class SquareImageView extends ImageView {

    // 控件默认长、宽
    private int defaultWidth = 0;
    private int defaultHeight = 0;
    // 比例
    private float scale = 1;

    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {

        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (getWidth() == 0) {
            return;
        }
        if(defaultWidth == defaultHeight && defaultWidth != 0){
            super.onDraw(canvas);
            return;
        }


        this.measure(0, 0);
        if (defaultWidth == 0) {
            defaultWidth = getWidth();
        }

        defaultHeight = (int) (defaultWidth * scale);
        ViewGroup.LayoutParams params = this.getLayoutParams();
        params.width = defaultWidth;
        params.height = defaultHeight;
        this.setLayoutParams(params);
        super.onDraw(canvas);

    }

}

